package org.dna.metronomo.persistence.impl;

import java.net.URL;
import org.apache.ibatis.io.Resources;
import org.apache.ibatis.io.Resources.IResourceLocator;
import org.dna.metronomo.persistence.IActivityDAO;
import org.dna.metronomo.persistence.IJobDAO;
import org.dna.metronomo.persistence.IUserDAO;
import org.osgi.framework.BundleActivator;
import org.osgi.framework.BundleContext;

/**
 * Activator class to publish the services of the persistence-iBatis2 module.
 * Publishes implementations for:
 *  - IActivityDAO
 *  - IUserDAO
 *  - IJobDAO 
 * */
public class MyBatisDAOsActivator implements BundleActivator {

    @Override
    public void start(final BundleContext context) throws Exception {
        System.out.println("context.xml:" + context.getBundle().
                getEntry("org/dna/metronomo/persistence/configuration.xml"));
        Resources.setDefaultResourceLocator(new IResourceLocator() {

            public String locate(String resource) {
                URL url = context.getBundle().getEntry(resource);
                if (url != null) {
                    return url.toString();
                }
                System.out.println("Can't find resource: " + resource);
                return "";
            }
        });
        //instantiate
        IBatisActivityDAO activityDAO = new IBatisActivityDAO();
        IUserDAO userDAO = new IBatisUserDAO();
        IJobDAO jobDAO = new IBatisJobDAO();
        activityDAO.createSchema();

        //publish
        context.registerService(IActivityDAO.class.getName(), activityDAO, null);
        context.registerService(IUserDAO.class.getName(), userDAO, null);
        context.registerService(IJobDAO.class.getName(), jobDAO, null);
    }

    @Override
    public void stop(BundleContext context) throws Exception {
        // nothing to do
    }
}
